package com.yidian.controller.business;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yidian.server.goods.SkuSearchService;
import com.yidian.utils.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author whb
 * @create 2021-06-29 13:28
 * @desciption elasticsearch搜索Sku数据的控制类
 */
@Controller
public class SearchController {
    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);//字符集处理（解决中文乱码问题）

        //当接收页码为空时，默认页码为1
        if (searchMap.get("pageNo")==null){
            searchMap.put("pageNo","1");
        }

        //当接收排序参数为空时，进行容错处理;sort:排序字段,sortOrder 排序规则(升序/降序)
        if (searchMap.get("sort")==null){//查询Map获取排序字段信息
            searchMap.put("sort","");
        }

        if (searchMap.get("sortOrder")==null){
            searchMap.put("sortOrder","DESC");
        }

        Map resultMap = skuSearchService.search(searchMap);
        model.addAttribute("result", resultMap);

        //拼接url
        StringBuffer url = new StringBuffer("/search.do?");
        if (searchMap.size() > 0) {
            for (String key : searchMap.keySet()) {
                url.append("&" + key + "=" + searchMap.get(key));
            }
        }
        model.addAttribute("url", url);

        model.addAttribute("searchMap",searchMap);

        //获取当前页码，传回页面
        Integer pageNo=Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //控制页面显示页码数量（默认设置显示5页）
        Integer startPage=1;//开始页码
        Long totalPages = (Long) resultMap.get("totalPages");//获取总页数
        Integer endPage=totalPages.intValue();//结束页码

        //当页码是1，或者总页数大于5时,或者结束页码大于总页数
        if (totalPages>5){
            startPage=pageNo-2;
            //开始页码小于，默认为1
            if (startPage<1){
                startPage=1;
            }
            //结束页码大于总页数，默认为总页数
            if ((startPage+4)<=totalPages){
                endPage=startPage+4;
            }
        }

        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        return "search";
    }
}
